﻿using System;
using System.Text;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing.Imaging;

namespace XoLib.Tools
{

    /// <summary>
    /// <example> ScreenShot.  </example>
    /// ScreenShot class
    /// </summary>
    public class ScreenShot
    {
        enum RasterOperation : uint { SRC_COPY = 0x00CC0020 }

#if WindowsCE
        [DllImport("coredll.dll")]
#else
        [DllImport("Gdi32.dll")]
#endif      
        private static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, RasterOperation rasterOperation);


#if WindowsCE
        [DllImport("coredll.dll")]
#else
        [DllImport("User32.dll")]
#endif      
        private static extern IntPtr GetDC(IntPtr hwnd);

#if WindowsCE
        [DllImport("coredll.dll")]
#else
        [DllImport("User32.dll")]
#endif
        private static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc);


        /// <summary>
        /// Take the screen shot
        ///  <example> ScreenShot.Take()  </example>
        ///  <returns>Bitmap</returns>
        /// </summary>
        static public Bitmap Take()
        {
            Rectangle bounds = Screen.PrimaryScreen.Bounds;
            IntPtr hdc = GetDC(IntPtr.Zero);
            Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format16bppRgb565);
            using (Graphics graphics = Graphics.FromImage(bitmap))
            {
                IntPtr dstHdc = graphics.GetHdc();
                BitBlt(dstHdc, 0, 0, bounds.Width, bounds.Height, hdc, 0, 0,
                RasterOperation.SRC_COPY);
                graphics.ReleaseHdc(dstHdc);
            }            
            ReleaseDC(IntPtr.Zero, hdc);
            return bitmap;
        }


        /// <summary>
        /// Take and save in date file
        ///  <example> ScreenShot.TakeAndDate(@"c:\")  </example>
        ///  <returns>string</returns>
        /// </summary>
        static public string TakeAndDate(string Path)
        {
            string file = Path + "\\" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".jpg";
            Take().Save(file, ImageFormat.Jpeg);
            return file;            
        }

        /// <summary>
        /// Take the screen shot
        /// <para>string</para>
        ///  <example> ScreenShot.TakeAndSave("Image.jpg")  </example>
        /// </summary>
        static public void TakeAndSave(string file)
        {
            Take().Save(file, ImageFormat.Jpeg);
        }



    }
}
